package com.artifact.mit.mypoint.async;

import static com.artifact.mit.mypoint.util.Variable.SHARED_POINT;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.artifact.mit.mypoint.activity.MyPointBaseActivity;
import com.artifact.mit.mypoint.model.api.Point;
import com.artifact.mit.mypoint.service.ServiceHandler;
import com.artifact.mit.mypoint.util.FormatHelper;

public class PointAsync extends AsyncTask<String, Void, Point> {
	
	private TextView pointValue;
	private Context pointAsyncContext;	
	private ServiceHandler serviceHandler;
	
	public PointAsync(Context context, TextView point) {
		pointAsyncContext = context;
		pointValue = point;
		serviceHandler = new ServiceHandler(context);
	}
	
	@Override
	protected void onPreExecute() {
		setProgress(View.VISIBLE);
	}
	
	@Override
	protected void onPostExecute(Point result) {		
		if(result != null){
			if(!"".equals(result.getUserPointBook().getSaldo())){	
				String point = FormatHelper.formatNumber(result.getUserPointBook().getSaldo());
				pointValue.setText(point);
			
				serviceHandler.commitEditor(SHARED_POINT, result.getUserPointBook().getSaldo());
//				MyPointBaseActivity activity = ((MyPointBaseActivity)pointAsyncContext); 
//				if (activity != null)
//					((MyPointBaseActivity) pointAsyncContext).setPoint(point);
				setProgress(View.GONE);					
				return;
			}
		} else {
			pointValue.setText("0");			
			setProgress(View.GONE);		
		}
	}
	
	@Override
	protected Point doInBackground(String... arg0) {
//		MyPointBaseActivity activity = ((MyPointBaseActivity) pointAsyncContext);
//		if (activity != null) {
//			try {
//				return serviceHandler.pointService();
//			} catch (Exception e) {
//				Log.e(this.getClass().getName(), "Error Point Service", e);
//			}
//		}
		try {
			return serviceHandler.pointService();
		} catch (Exception e) {
			Log.e(this.getClass().getName(), "Error Point Service", e);
		}
		return null;
	}
	
	private void setProgress(int visibility){
		MyPointBaseActivity activity = ((MyPointBaseActivity) pointAsyncContext);
		if (activity != null)
			activity.setProgressBar(visibility);
	}	
}